﻿using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Windows.Networking.NetworkOperators;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WlanAutoOpen
{
    public partial class MainForm : Form
    {
        string settingPath = Application.StartupPath + "/config/localsetting.json";
        LocalSetting globalSetting = new LocalSetting();
        public MainForm()
        {
            InitializeComponent();
            initConfig();
            AutoRunProxy.Instance().doWorkEvent += doWork;
        }
        private void initConfig()
        {
            try
            {
                if (!Directory.Exists(Application.StartupPath + "/config"))
                    Directory.CreateDirectory(Application.StartupPath + "/config");
                string jsonStr = File.ReadAllText(settingPath);
                globalSetting = JsonConvert.DeserializeObject<LocalSetting>(jsonStr);
                if (globalSetting != null)
                {
                    txt_name.Text = globalSetting.name;
                    txt_pwd.Text = globalSetting.password;
                    cbox_auto.Checked = globalSetting.autoStart;
                    if (globalSetting.autoStart)
                    {
                        AutoRunProxy.Instance().Start();
                    }
                }
            }
            catch { }
        }
        private void btn_start_Click(object sender, EventArgs e)
        {
            string name = txt_name.Text;
            string pwd = txt_pwd.Text;

            globalSetting.name = name;
            globalSetting.password = pwd;
            globalSetting.autoStart = cbox_auto.Checked;
            string settingJsonStr = JsonConvert.SerializeObject(globalSetting);
            File.WriteAllText(settingPath, settingJsonStr);

            //开机自启
            autoStart(cbox_auto.Checked);
            if (cbox_auto.Checked)
            {
                AutoRunProxy.Instance().Start();
            }
            else
            {
                AutoRunProxy.Instance().Start(1);
            }

        }
        public void WriteLog(string message) {
            //文字超长清空
            if (txtLog.Text.Length > 1000)
            {
                txtLog.Invoke(new Action(() =>
                {
                    txtLog.Text = "";
                }));
            }

            txtLog.Invoke(new Action(() =>
            {
                txtLog.Text = DateTime.Now.ToString("MM-dd HH:mm:ss->") + message + "\r\n" + txtLog.Text;
            }));
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Maximized;
                this.notifyIcon1.Visible = true;
                this.Hide();
                return;
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.notifyIcon1.Visible = false;
            this.Close();
            this.Dispose();
            System.Environment.Exit(System.Environment.ExitCode);
        }

        public void autoStart(bool flag)
        {
            try
            {
                string applicationName = Process.GetCurrentProcess().MainModule.ModuleName;
                string applicationPath = Process.GetCurrentProcess().MainModule.FileName;
                if (flag)
                {
                    RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

                    var item = registryKey.GetValue(applicationName);
                    if (item == null)
                    {
                        registryKey.SetValue(applicationName, applicationPath);
                    }

                }
                else
                {
                    RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

                    var item = registryKey.GetValue(applicationName);
                    if (item != null)
                    {
                        registryKey.DeleteValue(applicationName);
                    }
                    AutoRunProxy.Instance().Stop();
                }
            }
            catch (Exception ex) {
                WriteLog(ex.Message);
            }


        }

        
        public void doWork(){
            if(!string.IsNullOrEmpty(globalSetting.name)&&!string.IsNullOrEmpty(globalSetting.password))
            WriteLog( StartWifi(globalSetting.name, globalSetting.password));
         }
        public string StartWifi(string name, string password)
        {
            string messageStr = "";
            var connectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
            if (connectionProfile != null)
            {
                var tetheringManager = Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager.CreateFromConnectionProfile(connectionProfile);
                var access = tetheringManager.GetCurrentAccessPointConfiguration();
                

                //是否开启
                bool isStart = tetheringManager.TetheringOperationalState == TetheringOperationalState.On;
                if (!isStart||access.Ssid!=name)
                {
                    access.Ssid = name;
                    access.Passphrase = password;
                    var changeResult = tetheringManager.ConfigureAccessPointAsync(access);
                    if (changeResult.Status == Windows.Foundation.AsyncStatus.Started)
                    {
                        var result = tetheringManager.StartTetheringAsync();
                        if (result.Status == Windows.Foundation.AsyncStatus.Started)
                        {
                            //wifi热点开启成功
                            messageStr = ($"{Thread.CurrentThread.ManagedThreadId} 热点【{name}】开启成功");
                        }
                    }
                    else messageStr = $"{Thread.CurrentThread.ManagedThreadId} 热点启动失败";
                }
                else
                {
                    messageStr = ($"{Thread.CurrentThread.ManagedThreadId} 热点【{access.Ssid}】已经打开了");
                }
            }
            else
            {
                messageStr = ($"{Thread.CurrentThread.ManagedThreadId} 找不到网卡");

            }
            return messageStr;
        }

        private void btn_close_Click(object sender, EventArgs e)
        {

        }
    }
    public class LocalSetting
    {
        public string name { get; set; }
        public string password { get; set; }
        public bool autoStart { get; set; }
    }
}
